package exercise;

import java.io.*;
import java.util.Scanner;

/**
 * 扫描指定目录，并找到名称或者内容中包含指定字符的所有普通文件（不包含目录）
 */

public class Test3 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入源路径:>");
        String rootDirPath = scanner.nextLine();
        System.out.println("输入查询的关键字:>");
        String word = scanner.nextLine();
        File rootDir = new File(rootDirPath);
        if (!rootDir.isDirectory()){
            System.out.println("源路径错误");
            return;
        }
        scanDir(rootDir, word);
    }

    private static void scanDir(File rootFile, String word) throws IOException {
        //列出rootDir的内容
        File[] files = rootFile.listFiles();
        if (files == null){
            return ;
        }
        //遍历所有内容
        for (File f : files) {
            if (f.isFile()){
                if (containWord(f, word)){
                    System.out.println(f.getCanonicalPath());
                }
            }else if (f.isDirectory()){
                scanDir(f, word);
            }
        }
    }

    //把文件中的内容拿出来
    private static boolean containWord(File f, String word) {
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(f)){
            //对于字符输入用buffer
            char[] buffer = new char[1024];
            while (true){
                int len = reader.read(buffer);
                if (len == -1){
                    break;
                }
                stringBuilder.append(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // indexOf 返回的是子串的下标. 如果 word 在 stringBuilder 中不存在, 则返回下标为 -1
        return stringBuilder.indexOf(word) != -1;
    }
}
